[C - Socket] UDP CLIENT
Publicado por Enzo de Brito Ferber 10/03/2006
[ Hits: 12.210 ]
Homepage: http://www.maximasonorizacao.com.br
Este script testei na minha
propria máquina em terminas
diferentes, mas creio eu que
funcionará em uma rede local.
Como fazer funcionar:
Compile o script:
cc -o client client.c
Abra um terminal (xterm)
Execute o servidor.
Abra outro terminal (xterm)
Execute o cliente
P.S.: O servidor está em
outro link
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#define PORT 3456
int main(int argc, char *argv[]){
int fd1, fd2;
int num_b;
int len_msg;
char msg[100];
struct sockaddr_in client;
struct sockaddr_in server;
struct hostent *host;
if(argc != 2){
printf("Error!!! %s <host>\n", argv[0]);
exit(1);
}
host = gethostbyname(argv[1]);
if(host == NULL){
printf("Impossivel resolver endereco do servidor...\n");
exit(1);
}
fd1 = socket(AF_INET, SOCK_DGRAM, 0);
if(fd1 == -1){
perror("socket");
exit(1);
}
client.sin_family = AF_INET;
client.sin_port = htons(PORT);
client.sin_addr.s_addr = INADDR_ANY;
server.sin_family = host->h_addrtype;
server.sin_port = htons(PORT);
memcpy((char *) &server.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
bzero(&(client.sin_zero), 8);
bzero(&(server.sin_zero), 8);
fd2 = connect(fd1, (struct sockaddr *)&server, sizeof(struct sockaddr));
if(fd2 == -1){
perror("connect");
exit(1);
}
memset(msg, 0x0, 100);
while(1){
printf("Digite uma mensagem (exit para sair): ");
fflush(stdin);
scanf("%[^\n]", msg);
len_msg = sizeof(msg);
sendto(fd1, msg, len_msg, 0, (struct sockaddr *)&server, sizeof(struct sockaddr));
if( (strcmp("exit", msg)) == 0){
printf("\nObrigado por usar este cliente...\n");
break;
}
getchar();
}
close(fd1);
close(fd2);
}
Funções básicas para conexão OpenSSL em C
Programa em C para monitorar IPs e portas ativas
Modo Simples de Baixar e Usar o bash-completion
Monitorando o Preço do Bitcoin ou sua Cripto Favorita em Tempo Real com um Widget Flutuante
Instalando partes faltantes do Plasma 6
Adicionar botão "mostrar área de trabalho" no Zorin OS
Como montar um servidor de backup no linux
Estou tentando ser legalista, mas tá complicado! (9)
espelhar monitores nao funciona (2)
SQLITE não quer funcionar no LINUX LMDE6 64 com Lazaruz 4.2 64bit (n... (1)









